package com.example.httpmessageconverter.config;

import com.example.httpmessageconverter.entity.DemoObj;
import com.example.httpmessageconverter.entity.TypeEnum;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class CustomHttpMessageConverter implements HttpMessageConverter {
    @Override
    public boolean canRead(Class clazz, MediaType mediaType) {
        //可读开关
        return clazz == DemoObj.class;
    }

    @Override
    public boolean canWrite(Class clazz, MediaType mediaType) {
        //可写开关
        return true;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        //定制媒体类型，可以在具体类型下执行
        return MediaType.parseMediaTypes("application/json");
    }

    @Override
    public Object read(Class clazz, HttpInputMessage inputMessage) throws HttpMessageNotReadableException {
        //定制参数解析
        try {
            InputStream body = inputMessage.getBody();
            char c[] = new char[100];
            for (int i = 0; i < 100; i++) {
                c[i] = (char) body.read();
                System.out.print(c[i]);
            }
            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new DemoObj(11L,"33", TypeEnum.LOGIN);
    }

    @Override
    public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException, IOException {
        //定制响应逻辑
        outputMessage.getBody().write("ffff".getBytes());
        outputMessage.getBody().flush();
    }
}